<!-- 搜索历史 -->
<template>
    <div class="sdy-search-history">
        <div class="history box" v-if="historyList.length">
            <div class="title" >
                <span>最近搜索</span>
                <van-icon class="del" name="delete-o" @click="clearHistoryHandler"/>
            </div>
            <ul>
                <li @click="clickHandler" v-for="item in historyList">{{item}}</li>
            </ul>
        </div>
        <div class="hot box">
            <div class="title">
                <span>热门搜索</span>
                <span @click="isShow=!isShow">{{isShow ? '隐藏' : '显示' }}</span>
            </div>
            <ul v-if="isShow" class="content">
                <li
                v-for="item in hotList"
                :key="item.wordid"
                @click="clickHandler">{{item.keyword}}</li>
            </ul>
            <div v-else class="hid">已经隐藏搜索发现</div>
        </div>
        </div>

</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import type { Router } from 'vue-router';
// 导入请求api
import { hotSearchApi } from '@/api/goods'
// 导入对应的ts接口
import type { MyHotSearchItem} from '@/config/interface'

const $router : Router  = useRouter () 

// 定义一个数组保存历史记录
const historyList = ref(JSON.parse(window.localStorage.getItem('history') as string)  || [])

// 准备一个变量控制底部hid
const isShow = ref<boolean>(true)

// 点击搜索按钮跳转分类页面
const clickHandler = (e: Event) => { 
    const text = (e.target as HTMLElement).innerText
    // console.log(text);

    // 需要跳转路由，携带text去到商品列表页
    $router.push({ path: '/list', query: { search : text }})
}

//点击垃圾桶清空搜索记录
const clearHistoryHandler = () => { 
    window.localStorage.removeItem('history')
    historyList.value = []
}

//准备搜索列表
const hotList = ref<MyHotSearchItem[]>([])

//挂载完毕后请求数据
onMounted(async () => { 
    const res = await hotSearchApi()
    // console.log(res);
    hotList.value = res.data
})
</script>
<style scoped lang="scss">
.sdy-search-history{
    height: 100%;
    box-sizing: border-box;
    padding: 15px;
    >.box{
        margin-bottom: 30px;
        >.title{
            display: flex;
            justify-content: space-between;
            >.del{
            font-size: 20px;
            }
        }
        >ul{
            display: flex;
            flex-wrap: wrap;
            margin-top: 5px;
            >li{
                background-color: #c4c4c4;
                color: #fff;
                padding: 2px 3px;
                margin: 0 2px;
            }
        }
        >.hid{
            height: 100%;
            margin-top: 50px;
            display: flex;
            justify-content: center;
            align-content: center;
        }
    }
}
</style>